﻿
Imports System.IO
Imports std
Imports xmlctrl

Public Class backgroundDownloader
    Inherits container

    Public Const triggerFunctionName As String = "bgdltrg"
    Private _page As xhtmlpage = Nothing
    Private _l As list(Of String) = Nothing

    Public Sub New(ByVal page As xhtmlpage, Optional ByVal s As Stream = Nothing)
        MyBase.New(s)
        _l = New list(Of String)()
        _page = page
    End Sub

    Public Sub add(ByVal url As String)
        _l.insert(url)
    End Sub

    'this should go before inlineScript
    Protected Overrides Function render(ByVal compress As Boolean) As Boolean
        Dim inlineScript As inlineScript = Nothing
        If Not _page Is Nothing AndAlso _l.size() > 0 Then
            inlineScript = _page.inlineScript()
            _page.endInlineScript().addscript(triggerFunctionName + ".trigger", triggerFunctionName + "();")
            Dim arrayContent As String = Nothing
            For i As Int64 = 0 To _l.size() - 1
                If i > 0 Then
                    arrayContent += ","
                End If
                arrayContent += _l(i)
            Next
            inlineScript.addscript(triggerFunctionName, _
                                   "function " + triggerFunctionName + "(){" + _
                                   "var a=new Array(" + arrayContent + ");" + _
                                   "for(var u in a){" + backgroundDownload.invoke(inlineScript, "a[u]") + ";}}")
        End If
        Return True
    End Function
End Class
